package thread;
// 完成 MyTimer的自己实现

import java.util.PriorityQueue;
import java.util.concurrent.BlockingQueue;

class MyTimerTask2 implements Comparable<MyTimerTask2>{
    private Runnable runnable;
    private long time;
    public MyTimerTask2(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }
    public long getTime(){
        return time;
    }
    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer2{
    private Object locker = new Object();
    private PriorityQueue<MyTimerTask2> queue = new PriorityQueue<>();
    private Thread t = null;
    public MyTimer2(){
        t = new Thread(() ->{
            while(true){
                synchronized (locker){
                    try {
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask2 task2 = queue.peek();
                        long time = System.currentTimeMillis();
                        if(time >= task2.getTime()){
                            queue.poll();
                            task2.run();
                        } else {
                            locker.wait(task2.getTime() - time);
                        }
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
            }

        });
        t.start();
    }
    public void schedule(Runnable runnable,long delay){
        synchronized (locker){
            MyTimerTask2 task2 = new MyTimerTask2(runnable,delay);
            queue.offer(task2);
            locker.notify();
        }
    }

}

public class ThreadDemo30 {
    public static void main(String[] args) {
        MyTimer2 timer2 = new MyTimer2();
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        timer2.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        System.out.println("hello main");
    }
}
